package sensor

import (
	"encoding/binary"
	"fmt"
	//"strings"
	"time"
	//"unicode"
	"log"
	"math"
)

// COParser 一氧化碳传感器解析器
type COParser struct {
	expectedLength int
}

func NewCOParser(dataLength int) *COParser {
	return &COParser{
		expectedLength: dataLength,
	}
}

func (p *COParser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		log.Printf("CO数据长度错误: 期望%d字节, 实际%d字节", p.expectedLength, len(data))
		return false
	}
	
	// 检查起始位是否为0xFF
	if data[0] != 0xFF {
		log.Printf("CO起始位错误: 期望0xFF, 实际0x%X", data[0])
		return false
	}
	
	// 正确的校验和计算：从第2字节到第8字节求和，然后计算补码
	sum := byte(0)
	for i := 1; i < 8; i++ { // 从第2字节(索引1)到第8字节(索引7)
		sum += data[i]
	}
	
	// 计算补码：256 - sum
	calculatedChecksum := byte(256 - int(sum))
	actualChecksum := data[8]
	
	if calculatedChecksum != actualChecksum {
		log.Printf("CO校验和错误: 计算值0x%X, 实际值0x%X", calculatedChecksum, actualChecksum)
		log.Printf("详细计算: 字节[1-7]和=0x%X, 补码=256-0x%X=0x%X", 
			sum, sum, calculatedChecksum)
		return false
	}
	
	// log.Printf("CO校验和正确: 0x%X", calculatedChecksum)
	return true
}

func (p *COParser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid CO data format")
	}

	// 解析气体名称（ASCII字符）
	gasName := string(data[1])
	
	// 解析单位（ASCII字符）
	unit := "unknown"
	if (data[2] == 0x11) {
		unit = "MG/M3"
	}
	
	// 解析小数点位数
	decimalPlaces := int(data[3])
	
	// 解析浓度值（大端序，16位无符号整数）
	concentrationRaw := binary.BigEndian.Uint16(data[4:6])
	concentrationValue := float64(concentrationRaw)
	
	// 解析满量程值（大端序，16位无符号整数）
	fullScaleRaw := binary.BigEndian.Uint16(data[6:8])
	fullScaleValue := float64(fullScaleRaw)
	
	// 根据小数点位数调整实际值
	if decimalPlaces > 0 {
		divisor := math.Pow10(decimalPlaces)
		concentrationValue = concentrationValue / divisor
		fullScaleValue = fullScaleValue / divisor
	}
	
	// 根据气体名称确定传感器类型
	sensorType := "unknown"
	switch gasName {
	case "C":
		sensorType = "co"
	case "4": // TVOC
		sensorType = "tvoc"
	case "N": // NO2
		sensorType = "no2"
	case "S": // SO2
		sensorType = "so2"
	}
	
	// log.Printf("CO传感器解析结果: 类型=%s, 气体=%s, 单位=%s, 小数点位数=%d, 浓度=%.2f, 满量程=%.3f", 
	// 	 sensorType, gasName, unit, decimalPlaces, concentrationValue, fullScaleValue)
	
	return &SensorData{
		SensorType: sensorType,
		Values: map[string]interface{}{
			"gas_name":          gasName,
			"unit":              unit,
			"decimal_places":    decimalPlaces,
			"concentration":     concentrationValue,
			"full_scale":        fullScaleValue,
			"concentration_raw": concentrationRaw,
			"full_scale_raw":    fullScaleRaw,
		},
		RawData:   fmt.Sprintf("%X", data),
		Timestamp: time.Now(),
	}, nil
}